package org.rpc.proj.curator;

import com.alibaba.fastjson.JSONObject;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

public class CuratorTest {


    private static final String CONNECTION_STRING = "127.0.0.1:2181";

    private static CuratorFramework client = null;

    //超时时间
    private static final int TIME_OUT = 6000;

    @Before
    public void init() throws Exception {
        //初始休眠时间、休眠次数、最大休眠时间
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 5, 6000);
        client = CuratorFrameworkFactory.builder()
                .retryPolicy(retryPolicy)
                .connectString(CONNECTION_STRING)
                .sessionTimeoutMs(TIME_OUT)
                .build();

        client.start();

        Thread.sleep(3000);
    }

    /**
     * 查看节点信息
     */
    @Test
    public void queryNode() throws Exception{

        Stat stat = client.checkExists().forPath("/aaa");

        String data = JSONObject.toJSONString(stat);

        System.out.println(data);
    }


    /**
     * 获取节点值
     */
    @Test
    public void getNodeValue() throws Exception{

        byte[] result = client.getData().forPath("/aaa");

        String data = new String(result,"utf-8");

        System.out.println(data);
    }

    /**
     * 获取节点值
     */
    private void getNodeValue(String node) throws Exception{

        byte[] result = client.getData().forPath(node);

        String data = new String(result,"utf-8");

        System.out.println(data);
    }


    /**
     * 创建节点
     */
    @Test
    public void create() {
        try {
            String data = "first_data";
            client.create().withMode(CreateMode.PERSISTENT).forPath("/aaa", data.getBytes());
        } catch (Exception e) {
            System.out.println("创建节点失败" + e.getMessage());
        }
    }

    /**
     * 修改节点值
     */
    @Test
    public void updateNode() throws Exception{
        String node = "/aaa";
        String data = "second_data";
        client.setData().forPath("/aaa",data.getBytes());
        System.out.println("节点值修改成功");
        getNodeValue(node);
    }

    /**
     * 创建一个节点值bbb，并删除
     */
    @Test
    public void deleteNode() throws Exception{
        String node = "/bbb";
        String nodeValue = "bbb";
        client.create().forPath(node,nodeValue.getBytes());

        Stat stat = client.checkExists().forPath(node);

        String data = JSONObject.toJSONString(stat);

        System.out.println("data = " + data);

        System.out.println("=====================");

        //client.delete().forPath(node);

        //System.out.println("节点值删除成功");

    }

}
